import { ValueEnum, Option } from '../types';

/**
 * 判断数据类型
 */
export function checkType(target: unknown) {
  if (target instanceof Promise) {
    return 'Promise';
  } else if (typeof target === 'function') {
    return 'Function';
  } else if (target !== null && typeof target === 'object') {
    return 'Object';
  } else {
    return 'Other';
  }
}

/**
 * valueEnum 转 options
 */
export const valueEnumToOptions = (
  valueEnum: ValueEnum,
  type?: any,
): Option[] => {
  return Object.keys(valueEnum).map((key) => {
    return {
      label: valueEnum[key].text,
      value: type && type === 'int' ? Number(key) : key,
      disabled: valueEnum[key].disabled,
    };
  });
};

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
export function handleTree(
  data: any,
  id?: any,
  parentId?: any,
  children?: any,
) {
  let config = {
    id: id || 'id',
    parentId: parentId || 'parentId',
    childrenList: children || 'children',
  };

  let childrenListMap: Record<string, any> = {};
  let nodeIds: Record<string, any> = {};
  let tree = [];

  for (let d of data) {
    let parentId = d[config.parentId];
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = [];
    }
    nodeIds[d[config.id]] = d;
    childrenListMap[parentId].push(d);
  }

  for (let d of data) {
    let parentId = d[config.parentId];
    if (nodeIds[parentId] == null) {
      tree.push(d);
    }
  }

  for (let t of tree) {
    adaptToChildrenList(t);
  }

  function adaptToChildrenList(o: { [x: string]: any }) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]];
    }
    if (o[config.childrenList]) {
      for (let c of o[config.childrenList]) {
        adaptToChildrenList(c);
      }
    }
  }
  return tree;
}
